package com.shop.loan.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.model.view.RentalDataBalanceLog;
import com.shop.loan.rentaldata.RentalDataUtil;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class RentalDataBalanceLogProxy implements DataProxy<RentalDataBalanceLog> {

    @Resource
    RentalDataUtil rentalDataUtil;

    @Resource
    Util util;

    @Override
    public String beforeFetch(List<Condition> conditions) {
        conditions.removeIf(condition -> "type".trim().equals(condition.getKey()));
        return null;
    }

    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        list.clear();

        String pageIndexStr = util.getSearchParam("pageIndex", 1);
        String pageSizeStr = util.getSearchParam("pageSize", 1);
        String typeStr = util.getSearchParam("type", 1);
        Integer pageNum = pageIndexStr == null ? 1 : Integer.parseInt(pageIndexStr);
        Integer pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);
        Integer type = typeStr == null ? null : Integer.parseInt(typeStr);
        JSONObject dataJs = rentalDataUtil.getBalanceLog(pageNum, pageSize, type);
        if (dataJs.containsKey("data")) {
            JSONArray array = dataJs.getJSONArray("data");
            Integer total = dataJs.getInteger("total");
            Integer pages = dataJs.getInteger("pages");
            for (Object o : array) {
                Map map = JSON.parseObject(JSON.toJSONString(o), Map.class);

                map.put("pageIndex",pageNum);
                map.put("pageSize",pageSize);
                map.put("total",total);
                map.put("totalPage",pages);
                list.add(map);
            }
        }
    }
}
